package org.chench.extra.logsift.config.properties;

import cn.hutool.core.util.ArrayUtil;
import org.apache.commons.lang3.StringUtils;
import org.chench.extra.logsift.bo.LogApp;
import org.chench.extra.logsift.enums.ForwardType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 应用全局配置参数
 * @author chench
 * @date 2025.05.17
 */
@Configuration
public class AppProperties {
    private static final Logger logger = LoggerFactory.getLogger(AppProperties.class);

    /** 指针文件路径 */
    @Value("${pointerFilePath}")
    private String pointerFilePath;

    /** 需要监控日志变化的应用名，用英文逗号分隔 */
    @Value("${log.app.names}")
    private String logAppNames;

    private Environment env;
    private Map<String, LogApp> logAppMap;

    @PostConstruct
    public void parseLogApps() {
        // 从启动参数中读取指针文件路径，优先使用
        String pointerFilePath = System.getProperty("pointer.file.path");
        if (StringUtils.isNotEmpty(pointerFilePath)) {
            this.pointerFilePath = pointerFilePath;
        }

        String[] logApps = this.logAppNames.split(",");
        if (ArrayUtil.isEmpty(logApps)) {
            logger.warn("parse log apps is empty!");
            return;
        }

        int initSize = (int) (logApps.length/0.75);
        Map<String, LogApp> logAppMap = new HashMap<>(initSize);
        for (String appName : logApps) {
            String forwardTypeKey = String.format("log.app.%s.forwardType", appName);
            String forwardTypeValue = this.env.getProperty(forwardTypeKey);
            if (StringUtils.isBlank(forwardTypeValue)) {
                throw new IllegalArgumentException(String.format("Empty [%s] value : %s", forwardTypeKey, forwardTypeValue));
            }

            String[] forwardTypeArr = forwardTypeValue.split(",");
            List<ForwardType> forwardTypes = new ArrayList<>(forwardTypeArr.length);
            for (String type : forwardTypeArr) {
                ForwardType forwardType = ForwardType.resolveValueOf(type);
                if (forwardType == null) {
                    logger.error("Unknown [{}] value : {}}!", forwardTypeKey, type);
                }
                forwardTypes.add(forwardType);
            }

            String forwardUrlKey = String.format("log.app.%s.forwardUrl", appName);
            String forwardUrlValue = this.env.getProperty(forwardUrlKey);

            String filterLevelKey = String.format("log.app.%s.filterLevel", appName);
            String filterLevelValue = this.env.getProperty(filterLevelKey);

            String timestampPatternKey = String.format("log.app.%s.timestampPattern", appName);
            String timestampPatternValue = this.env.getProperty(timestampPatternKey);
            if (StringUtils.isBlank(timestampPatternValue)) {
                logger.warn("load {} value is empty!", timestampPatternKey);
            }

            String pathPatternKey = String.format("log.app.%s.pathPattern", appName);
            String pathPatternValue = this.env.getProperty(pathPatternKey);
            if (StringUtils.isBlank(pathPatternValue)) {
                logger.warn("load {} value is empty!", pathPatternKey);
            }

            String contentPatternKey = String.format("log.app.%s.contentPattern", appName);
            String contentPathValue = this.env.getProperty(contentPatternKey);
            if (StringUtils.isBlank(contentPathValue)) {
                logger.warn("load {} value is empty!", contentPatternKey);
            }

            LogApp logApp = new LogApp(pathPatternValue, contentPathValue);
            logApp.setAppName(appName);
            logApp.setForwardTypes(forwardTypes);
            logApp.setForwardUrl(forwardUrlValue);
            logApp.setFilterLevel(filterLevelValue);
            if (StringUtils.isNotBlank(timestampPatternValue)) {
                logApp.setTimestampPattern(timestampPatternValue);
            }
            logAppMap.put(appName, logApp);
        }
        this.logAppMap = logAppMap;
    }

    /**
     * 根据应用名称获取日志应用对象
     * @param appName
     * @return {@link LogApp}
     */
    public LogApp getLogApp(String appName) {
        return this.logAppMap.get(appName);
    }

    /**
     * 根据应用名称获取日志转发类型
     * @param appName
     * @return
     */
    public List<ForwardType> getForwardTypes(String appName) {
        LogApp logApp = getLogApp(appName);
        if (logApp != null) {
            return logApp.getForwardTypes();
        }
        return new ArrayList<>(0);
    }

    public String getPointerFilePath() {
        return pointerFilePath;
    }

    public void setPointerFilePath(String pointerFilePath) {
        this.pointerFilePath = pointerFilePath;
    }

    public String getLogAppNames() {
        return logAppNames;
    }

    public void setLogAppNames(String logAppNames) {
        this.logAppNames = logAppNames;
    }

    public Map<String, LogApp> getLogAppMap() {
        return logAppMap;
    }

    @Autowired
    public void setEnv(Environment env) {
        this.env = env;
    }
}